package com.superiron.scaffold.security.util;

import com.superiron.scaffold.security.detail.IotGlobalRole;
import com.superiron.scaffold.security.detail.IotGlobalUser;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;

/**
 * @author ：yzg
 * @date ：Created in 2022/6/23 11:48
 * @description：
 * @modified By：
 * @version: $
 */
public class UserUtil {
	
	public static IotGlobalUser getCurrentUser() {
		
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Object principal = authentication.getPrincipal();
		
		if (principal instanceof String) {
			return null;
		}
		
		IotGlobalUser loginUser = (IotGlobalUser) principal;
		
		return loginUser;
	}
	
	/**
	 * 是否有某个角色
	 *
	 * @param roleCode
	 *
	 * @return
	 */
	public static boolean haveRole(String roleCode) {
		
		boolean flag = false;
		
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Object principal = authentication.getPrincipal();
		
		if (principal instanceof String) {
			return false;
		}
		
		IotGlobalUser loginUser = (IotGlobalUser) principal;
		
		List<IotGlobalRole> iotGlobalRoles = (List<IotGlobalRole>) loginUser.getAuthorities();
		if (CollectionUtils.isNotEmpty(iotGlobalRoles)) {
			Long count = iotGlobalRoles.stream().filter(entity -> StringUtils.equals(entity.getCode(), roleCode)).count();
			flag = count > 0;
		}
		return flag;
	}
	
}
